#!/usr/bin/python3
# coding=utf-8
import sys
import json
import random


def memgraph_result(raw):
    '''
    fd = open("./test.json", 'r')
    raw = fd.read().strip()
    fd.close()
    '''
    postprocess_result = {
        "code": 0,
        "err_msg": "",
        "result": {}
    }
    if raw.find("memGraph") == -1:
        postprocess_result["code"] = 1
        postprocess_result["err_msg"] = f"Diagnosis failed:\n{raw}"
        print(json.dumps(postprocess_result, indent=4))
        return

    rawdata = json.loads(raw)

    memgraph = {}
    memgraph["app"] = rawdata["memGraph"]["userUsed"]
    memgraph["free"] = rawdata["memGraph"]["free"]
    memgraph["kernel"] = rawdata["memGraph"]["kernelUsed"]

    newmemgraph = {}
    newmemgraph["summary"] = "success"
    if "summary" in rawdata:
        newmemgraph["summary"] = rawdata["summary"]
    newmemgraph["dataMemEvent"] = {"data": {}}
    newmemgraph["dataMemEvent"]["data"] = [
        {"key": "Util", "value": round(rawdata["event"]["util"], 2)},
        {"key": "MemLeak",
            "value":  "NG" if rawdata["event"]["leak"] else "OK"},
        {"key": "MemcgLeak",
            "value": "NG" if rawdata["event"]["memcg"] else "OK"},
        {"key": "MemFrag",
            "value": "NG" if rawdata["event"]["memfrag"] else "OK"}
    ]

    newmemgraph["dataMemOverView"] = {"data": {}}
    newmemgraph["dataMemOverView"]["data"] = [
        {"key": i[0], "value": i[1]} for i in memgraph.items()]

    newmemgraph["dataKerMem"] = {"data": {}}
    newmemgraph["dataKerMem"]["data"] = [
        {"key": i[0], "value": i[1]} for i in rawdata["memGraph"]["kernel"].items()]

    newmemgraph["dataUserMem"] = {"data": {}}
    newmemgraph["dataUserMem"]["data"] = [
        {"key": i[0], "value": i[1]} for i in rawdata["memGraph"]["user"].items()]

    newmemgraph["dataCacheList"] = {"data": {}}
    newmemgraph["dataCacheList"]["data"] = [
        {"key": index, "Name": item["file"], "cached": item["cached"], "Task": ','.join(
            item["task"])}
        for index, item in enumerate(rawdata["filecacheTop"])]

    newmemgraph["dataProcMemList"] = {"data": {}}
    newmemgraph["dataProcMemList"]["data"] = [
        {"key": index, "task": item["comm"], "MemTotal": item["total_mem"],
            "RssAnon": item["RssAnon"], "RssFile": item["RssFile"]}
        for index, item in enumerate(rawdata["memTop"])]

    postprocess_result["result"] = newmemgraph
    print(json.dumps(postprocess_result, ensure_ascii=False))


def extract_params():
    path, res, task_id = sys.argv[1], "", sys.argv[2]
    with open(path, 'r') as tmp:
        res = tmp.read()
    return res, task_id


if __name__ == "__main__":
    res, _ = extract_params()
    memgraph_result(res)
